﻿using System;
using System.Collections.Generic;
using System.Text;
using AgencyManagerSystem.Model;
using AgencyManagerSystem.DataUpdater;
using AgencyManagerSystem.Common;
using AgencyManagerSystem.DataFetcher;

namespace AgencyManagerSystem.Core
{
    public class LoginUpdaterCreator:BaseUpdaterCreator<LoginModel>
    {
        public  LoginUpdater CreateLoginUpdaterInstance()
        {
            LoginUpdater loginUpdater = new LoginUpdater(new LoginFetcher());
            loginUpdater.DataUpdating += FlagAndApproveFlagValid;
            loginUpdater.DataUpdating += UserExists;
            loginUpdater.DataUpdating += PassworkNotEmpty;

            return loginUpdater;
        }

        private void UserExists(BaseUpdater<LoginModel> sender, DataUpdatingEventArgs<LoginModel> e)
        {
            if (e.Insert == null)
                return;
            UserFetcher userFetcher = new UserFetcher();
            UserModel userModel = userFetcher.Get(e.Insert.UserId);
            if (userModel == null)
            {
                LogHelper.Log(this.GetType().Name, String.Format("USEREXISTS:用户档案{0}存在检查不通过", e.Insert.UserId));
                e.Message = "不存在这个用户编号";
                e.Cancel = true;
            }
        }
        private void PassworkNotEmpty(BaseUpdater<LoginModel> sender, DataUpdatingEventArgs<LoginModel> e)
        {
            if (e.Insert == null)
                return;
            if (String.IsNullOrWhiteSpace(e.Insert.Password))
            {
                LogHelper.Log(this.GetType().Name, String.Format("PASSWORKNOTEMPTY:用户{0}密码不能为空", e.Insert.UserId));
                e.Message = "密码不能为空";
                e.Cancel = true;
            }
        }
        private void AvaliableCheck(BaseUpdater<LoginModel> sender, DataDeletingEventArgs<LoginModel> e)
        {
            if (e.Delete == null)
                return;
            if (e.Delete.Status == 1)
            {
                LogHelper.Log(this.GetType().Name, String.Format("AVALIABLECHECK:用户{0}目前为生效状态不能删除", e.Delete.UserId));
                e.Message = "用户正在生效不能删除";
                e.Cancel = true;
            }
        }
    }
}
